package com.ctcemti.mdm.project.sys.service.impl;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.ctcemti.mdm.common.exception.InvalidParamException;
import com.ctcemti.mdm.common.util.BatchOperationUtils;
import com.ctcemti.mdm.common.util.ExcelExportStylerImpl;
import com.ctcemti.mdm.common.util.ExcelParseUtils;
import com.ctcemti.mdm.common.util.JWTUtil;
import com.ctcemti.mdm.project.common.excelverifyhandler.ExcelVerifyHandlerForSysMaterialClassification;
import com.ctcemti.mdm.project.sys.dao.ResMaterialLibraryMapper;
import com.ctcemti.mdm.project.sys.dao.SysMaterialClassificationMapper;
import com.ctcemti.mdm.project.sys.entity.SysMaterialClassification;
import com.ctcemti.mdm.project.sys.entity.formdata.BaseReq;
import com.ctcemti.mdm.project.sys.service.ISysMaterialClassificationService;
import com.ctcemti.mdm.project.common.excelverifyhandler.ExcelVerifyHandlerForSysMaterialClassification;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import tk.mybatis.mapper.entity.Example;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.SQLException;
import java.util.*;

@Service
@Slf4j
public class SysMaterialClassificationServiceImpl implements ISysMaterialClassificationService {
    @Value("${ctcemti.errorfilepath}")
    private String errorfilepath;

    @Autowired
    private SysMaterialClassificationMapper sysMaterialClassificationMapper;

    @Autowired
    private ResMaterialLibraryMapper resMaterialLibraryMapper;


    @Transactional
    @Override
    public int deleteByPrimaryKey(Integer id) {
        return sysMaterialClassificationMapper.deleteByPrimaryKey(id);
    }

    @Transactional
    @Override
    public int insert(SysMaterialClassification record) {
        return sysMaterialClassificationMapper.insert(record);
    }

    @Transactional
    @Override
    public int insertSelective(SysMaterialClassification record) {
        return sysMaterialClassificationMapper.insertSelective(record);
    }

    @Override
    public SysMaterialClassification selectByPrimaryKey(Integer id) {
        return sysMaterialClassificationMapper.selectByPrimaryKey(id);
    }

    @Transactional
    @Override
    public int updateByIdSelective(SysMaterialClassification record) {
        return sysMaterialClassificationMapper.updateByIdSelective(record);
    }

    @Transactional
    @Override
    public int updateByPrimaryKey(SysMaterialClassification record) {
        return sysMaterialClassificationMapper.updateByPrimaryKey(record);
    }

    @Override
    public List<SysMaterialClassification> selectAllSysMaterialClassification() {
        return sysMaterialClassificationMapper.selectAll();
    }

    @Override
    public List<SysMaterialClassification> selectByPid(String s) {
        Example example = new Example(SysMaterialClassification.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("parentId",s);
        example.setOrderByClause("sort");//排序
        return sysMaterialClassificationMapper.selectByExample(example);
    }

    @Override
    public List<SysMaterialClassification> selectSysMaterialClassification(SysMaterialClassification SysMaterialClassification) {
        return sysMaterialClassificationMapper.select(SysMaterialClassification);
    }


    @Transactional
    @Override
    public int deleteByPrimaryKeys(String ids) {
        String idarray[] = ids.split(",");
        resMaterialLibraryMapper.deleteBySysMaterialClassificationId(idarray);//删除子类字典详细类
        sysMaterialClassificationMapper.deleteByPids(idarray);//删除子类字典法分类
        return sysMaterialClassificationMapper.deleteByIds(ids);
    }

    @Override
    public PageInfo<SysMaterialClassification> selectListByPid(String id, BaseReq baseReq) {
        PageHelper.startPage(baseReq.getPageIndex(),baseReq.getPageSize(),"sort");
        Example example = new Example(SysMaterialClassification.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("parentId",id);
        List<SysMaterialClassification> list = sysMaterialClassificationMapper.selectByExample(example);
        PageInfo<SysMaterialClassification> pageInfo =  new PageInfo<SysMaterialClassification>(list);
        return pageInfo;
    }

    @Override
    public List<SysMaterialClassification> selectSysMaterialClassificationByName(String name) {
        return sysMaterialClassificationMapper.selectSysMaterialClassificationByName(name);
    }

    @Transactional
    @Override
    public Map<String, Object> uploadFile(MultipartFile multipartFile, String category, HttpServletResponse response, HttpServletRequest request) throws SQLException, IOException, InvalidParamException {

        Map<String,Object> resultMap = new HashMap<String,Object>();
        ExcelImportResult<SysMaterialClassification> excelImportResult = ExcelParseUtils.importExcelMore(multipartFile,0,1,SysMaterialClassification.class,new ExcelVerifyHandlerForSysMaterialClassification(sysMaterialClassificationMapper));
        boolean flag = true;
        if(excelImportResult == null){
            resultMap.put("flag",flag);
        }else if(excelImportResult.getFailList().size()>0){//验证失败，重新写入excel，并保存
            String filename = UUID.randomUUID().toString();//获取新的文件名
            File folder = new File(errorfilepath);//文件夹
            if(!folder.exists()){
                boolean mkFlag = folder.mkdirs();
                if (mkFlag) {
                    log.error("未找到上传文件夹，新建文件夹");
                }
            }
            FileOutputStream fos = null;
            try {
                //fileOutputStream = new FileOutputStream(file);
                //excelImportResult.getWorkbook().write(fileOutputStream);
                List<SysMaterialClassification> slist = excelImportResult.getList();//获取所有成功项
                List<SysMaterialClassification> flist = excelImportResult.getFailList();//获取所有失败项
                slist.addAll(flist);
                Collections.sort(slist);
                ExportParams exportParams = new ExportParams(null,null,"错误列表");
                exportParams.setStyle(ExcelExportStylerImpl.class);
                Workbook workbook = ExcelExportUtil.exportExcel(exportParams,SysMaterialClassification.class, slist);
                fos = new FileOutputStream(errorfilepath+"/"+filename+".xls");
                workbook.write(fos);
            } catch (Exception e) {
                e.printStackTrace();
            }finally {
                if(fos!=null){
                    fos.close();
                }
            }
            flag = false;
            resultMap.put("flag",flag);
            resultMap.put("filecode",filename);
        }else{//成功验证，准备导入数据
            List<SysMaterialClassification> list = excelImportResult.getList();
            String loginId = JWTUtil.getLoginId(request.getHeader("Authorization"));
            for(SysMaterialClassification sysMaterialClassification:list){
                sysMaterialClassification.setCreator(loginId);//添加导入人
                //resMaterialLibrary.setCategory(Integer.valueOf(category));
            }
            //物资分类库批量插入
            BatchOperationUtils<SysMaterialClassification> batchOperationUtils = new BatchOperationUtils();
            batchOperationUtils.batchOperation(list, 200,var->sysMaterialClassificationMapper.insertBatch(var));

            resultMap.put("flag",flag);
        }
        return resultMap;
    }
}
